class ArticlesController < ApplicationController
  before_filter :login_required, :only => [ :new, :create ]

  # GET /articles
  # GET /articles.xml
  def index
    @articles = Article.find(:all)

    respond_to do |format|
      format.html # index.rhtml
      format.xml  { render :xml => @articles.to_xml }
    end
  end

  # GET /articles/1
  # GET /articles/1.xml
  def show
    @entry   = Entry.find params[:id]
    @comment = Comment.new :identity => logged_in? ? current_user.username : 'Anonymous', :link => logged_in? ? current_user.email : nil, :entry_id => @entry.id

    respond_to do |format|
      format.html { render :layout => 'layouts/front' }
      format.xml  { render :xml => @article.to_xml }
    end
  end

  # GET /articles/new
  def new
    @article = Article.new
    @weblog  = Weblog.find params[:id]
  end

  # GET /articles/1;edit
  def edit
    @article = Article.find(params[:id])
  end

  # POST /articles
  # POST /articles.xml
  def create
    @article = Article.new params[:article]
    @entry   = Entry.new   params[:entry] do |e|
      e.resource = @article
      e.user     = current_user
    end

    respond_to do |format|
      if @article.save && Holder.find(@entry.holder_id).entries << @entry && current_user.entries << @entry
        format.html { redirect_to weblog_url(@article.entry.holder.weblog) }
        format.xml  { head :created, :location => article_url(@article) }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @article.errors.to_xml }
      end
    end
  end

  # PUT /articles/1
  # PUT /articles/1.xml
  def update
    @article = Article.find(params[:id])

    respond_to do |format|
      if @article.update_attributes(params[:article])
        flash[:notice] = 'Article was successfully updated.'
        format.html { redirect_to article_url(@article) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @article.errors.to_xml }
      end
    end
  end

  # DELETE /articles/1
  # DELETE /articles/1.xml
  def destroy
    @article = Article.find(params[:id])
    @article.destroy

    respond_to do |format|
      format.html { redirect_to articles_url }
      format.xml  { head :ok }
    end
  end
end
